import serial
import struct
import time
import os

class SensorDataCollector:
    def __init__(self, port, baud_rate, command_hex, expected_length, packet_length, file_path):
        self.port = port
        self.baud_rate = baud_rate
        self.command = bytes.fromhex(command_hex)
        self.expected_length = expected_length
        self.packet_length = packet_length
        self.file_path = file_path
        self.count = 0

        # 检查并创建路径中的目录
        os.makedirs(os.path.dirname(file_path), exist_ok=True)
        self._prepare_txt_file()

    def _prepare_txt_file(self):
        # 如果文件存在，清空文件内容
        open(self.file_path, 'w').close()
        print(f"文件 {self.file_path} 已创建/清空。")

    def send_command(self, ser):
        ser.write(self.command)
        print("指令已发送：", self.command.hex().upper())

    def receive_data(self, ser):
        data = ser.read(self.expected_length)
        print("接收到的数据：", data.hex().upper())
        return data

    def process_data(self, data):
        float_size = 4
        sensor_data = []
        num_packets = len(data) // self.packet_length

        for i in range(num_packets):
            start = i * self.packet_length
            frame = data[start:start + self.packet_length]

            # 按照frame的结构提取指定部分的数据
            binary_data = bytes(frame[5:17] + frame[18:30] + frame[31:43] + frame[44:56])

            # 将数据切片成4字节的块
            slices = [binary_data[i:i + float_size] for i in range(0, len(binary_data), float_size)]

            # 将每个块转换为大端序列
            big_endian_data = [slice[::-1] for slice in slices]

            # 将大端序列的每个块转换为浮点数
            float_array = [struct.unpack('>f', slice)[0] for slice in big_endian_data]

            sensor_data.extend(float_array)  # 展平成一维数组

        return sensor_data

    def collect_sensor_data(self):
        with serial.Serial(self.port, self.baud_rate, timeout=1) as ser:
            self.send_command(ser)
            data = self.receive_data(ser)
            processed_data = self.process_data(data)
        return processed_data

    def save_to_txt(self, data):
        with open(self.file_path, 'a') as file:
            file.write(' '.join(map(str, data)) + '\n')
        print(f"数据已保存至 {self.file_path}")
        self.count += 1

    def run(self, interval):
        while True:  # 持续读取传感器数据
            sensor_data = self.collect_sensor_data()
            print(sensor_data)
            # 输出处理后的数据
            for i, value in enumerate(sensor_data):
                print(f"第{i + 1}个数据值的处理结果：{value}")

            # 保存当前数据到TXT
            self.save_to_txt(sensor_data)

            # 这里添加一个暂停时间，以控制读取频率
            time.sleep(interval)

#示例使用
if __name__ == "__main__":
    collector = SensorDataCollector(
        port='COM8',
        baud_rate=1000000,
        command_hex='5A000603035D',
        expected_length=348,
        packet_length=58,
        file_path='E:\\shixian.txt'
    )
    collector.run(interval=0.01)